
local cjson = require "cjson.safe"

function desensitize_phone(data)
    -- 定义手机号的正则表达式
    local phone_pattern = "性别"
    -- 替换符合手机号格式的数字
    return data:gsub(phone_pattern, "SEX_XinBIE")
end

function main()
    local chunk, eof = ngx.arg[1], ngx.arg[2]
    local buffered = ngx.ctx.buffered

    -- 检查响应头中的Content-Type
    local content_type = ngx.header["Content-Type"] or ""

    if not buffered then
        buffered = {}
        ngx.ctx.buffered = buffered
    end

    if eof then
        if #buffered > 0 and (content_type:match("text/html") or content_type:match("application/json")) then
            -- 当内容类型为HTML或JSON时，处理并脱敏响应体
            local response = table.concat(buffered)
            response = desensitize_phone(response)
            ngx.arg[1] = response
        else
            -- 对于其他内容类型（如CSS和JS），直接返回原始响应体
            ngx.arg[1] = table.concat(buffered)
        end
    else
        -- 缓存响应块直到EOF
        if chunk ~= "" then
            buffered[#buffered + 1] = chunk
        end
        ngx.arg[1] = nil
    end
end

main()

